package main

import (
	"bytes"
	"fmt"
	"github.com/sirupsen/logrus"
	"io"
	"os"
	"path"
)

const (
	ccBlack  = 0 //黑色
	ccRed    = 1 //红色
	ccGreen  = 2 //绿色
	ccYellow = 3 //黄色
	ccBlue   = 4 //蓝色
	ccPurple = 5 //紫色
	ccCya    = 6 //青色
	ccGrey   = 7 //灰色
)

type MyEntry struct {
	Prefix string
}

func SetFile(path string) (writers []io.Writer) {
	file, _ := os.OpenFile(path, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 8666)

	writers = []io.Writer{
		//输出到文件
		file,
		//输出到控制台
		os.Stdout,
	}

	return writers

}

func (m MyEntry) Format(entry *logrus.Entry) ([]byte, error) {
	//设置颜色
	var color int
	switch entry.Level {
	case logrus.ErrorLevel:
		color = ccRed
	case logrus.WarnLevel:
		color = ccYellow
	case logrus.InfoLevel:
		color = ccBlue
	case logrus.DebugLevel:
		color = ccGreen
	default:
		color = ccGrey
	}

	//设置Buffer缓冲区
	var b *bytes.Buffer
	if entry.Buffer == nil {
		b = &bytes.Buffer{}
	} else {
		b = entry.Buffer
	}

	//时间格式化
	fmtTime := entry.Time.Format("2006-01-02 15:04:05")

	//文件的行号
	fileval := fmt.Sprintf("%s:%d:%s", path.Base(entry.Caller.File), entry.Caller.Line, entry.Caller.Function)
	//设置格式
	fmt.Fprintf(b, "\033[3%dm [%s] \033[0m [%s]-[%s]-[%s]-[%s]  \n", color, entry.Level, m.Prefix, fileval, fmtTime, entry.Message)

	return b.Bytes(), nil

}

func main() {
	logrus.SetReportCaller(true)
	logrus.SetLevel(logrus.DebugLevel)
	logrus.SetFormatter(&MyEntry{
		Prefix: "gin",
	})

	//设置文件输出路径
	writers := SetFile("log/logs.log")
	logrus.SetOutput(io.MultiWriter(writers...))

	logrus.Error("你好error")
	logrus.Warnln("你好Warnln")
	logrus.Info("你好info")
	logrus.Debug("你好Debug")

}
